package com.woyao.core.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by summerwind on 2016-06-26.
 */
public class ImageLoader {
    private String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
    public static void load(final ImageView imageView, final String url){
        if (! StringUtil.notNullOrEmpty(url)) {
          return;
        }

        AsyncTask<Void,Void,Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            Bitmap bm;
            @Override
            protected Boolean doInBackground(Void... params) {
                bm = getImageBitmap(url);
                return bm != null;
            }
            @Override
            protected void onPostExecute(Boolean result){
                if(result){
                    imageView.setImageBitmap(bm);
                }
            }
        };
        task.execute();
    }
    private static Bitmap getImageBitmap(String url) {
        Bitmap bm = null;
        try {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
        } catch (IOException e) {
//            Log.e(TAG, "Error getting bitmap", e);
        }
        return bm;
    }
}
